package com.schx.budget.controller;

import com.schx.budget.config.FilePathConfig;
import com.schx.budget.dto.FileUploadDTO;
import com.schx.budget.pojo.FileMsg;
import com.schx.budget.service.FileService;
import com.schx.budget.util.FileUtil;
import com.schx.budget.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * @Classname FileService
 * @Description TODO
 * @Date 2021/2/3 14:50
 * @Created by cyh
 */
@RestController
public class FileController {


    @Autowired
    private FileService fileService;

    @PostMapping("/uploadFile")
    public String fileUpload(@RequestParam("file") MultipartFile file,
                             @RequestParam("username") String username
                             ,@RequestParam("time") String time){

        FileUploadDTO fileUploadDTO = new FileUploadDTO(file.getOriginalFilename());
        fileUploadDTO.setSource(file);
        fileUploadDTO.setUsername(username);
        fileUploadDTO.setUploadTime(time);

        Boolean flag = fileService.fileUpload(fileUploadDTO);
        if(flag) {
            return "上传成功！";
        }else{
            return "上传失败！";
        }
    }


    @GetMapping("/fileList/fileName")
    public List<FileMsg> getFileListByFileName(@RequestParam("fileName") String fileName){
        return fileService.queryFileListByFileName(fileName);
    }

    @GetMapping("/fileList")
    public List<FileMsg> getFileList(Integer page,Integer limit, String orgid) {
        return fileService.getFileList(PageUtil.start(page, limit), PageUtil.end(page, limit), orgid);
    }

    @GetMapping( "/download")
    public void downloadFile(String path, HttpServletRequest request, HttpServletResponse response) {
        String url=FilePathConfig.PATH +path;
        File file = new File(url);
        String fileName = path;
        FileUtil.downloadFile(fileName,file,response,request);
    }


    @PostMapping("/delFile")
    public String deleteFile(@RequestBody()String fileName){
        String path=FilePathConfig.PATH+fileName;
        File file=new File(path);
        boolean flag = fileService.deleteFile(file, fileName);
        //删除文件
        if(flag) {
            return "删除成功！";
        }else{
            return "删除失败！";
        }

    }
}
